<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex; margin: 0 auto; justify-content: space-between;">
      <div>
        <el-input
          v-model.trim="queryParams.code"
          placeholder="编码"
          clearable
          style="width: 160px;"
          class="filter-item split-item"
        />
        <el-input
          v-model.trim="queryParams.name"
          placeholder="名称"
          clearable
          style="width: 160px;"
          class="filter-item split-item"
        />
        <el-select v-model="queryParams.parentCode" clearable placeholder="上级分类" style="width: 160px;" class="filter-item split-item">
          <el-option
            v-for="item in parentList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          plain
          @click="handleFilter"
        >查询</el-button>
        <el-button
          v-waves
          class="filter-item"
          plain
          icon="el-icon-refresh"
          @click="resetQueryParams"
        >重置
        </el-button>
      </div>
      <div style="margin-right: 50px;">
        <el-button
          v-permission="['iam:role:create']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          @click="onCreateItem"
        >新增
        </el-button>
        <el-button
          v-permission="['iam:role:edit']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          :disabled="itemTableSelectedCount !== 1"
          @click="onEditItem"
        >修改
        </el-button>
        <el-button
          v-permission="['iam:role:delete']"
          v-waves
          class="filter-item"
          plain
          size="mini"
          :disabled="itemTableSelectedCount <= 0"
          @click="onRemoveItem"
        >删除
        </el-button>
      </div>
    </div>

    <!-- itemTable -->
    <el-table
      ref="itemTable"
      v-loading="itemListLoading"
      v-el-height-adaptive-table="{bottomOffset: 70}"
      row-key="id"
      :data="itemList"
      border
      fit
      highlight-current-row
      class="item-table"
      height="100px"
      :cell-style="{padding:'5px'}"
      :header-cell-style="{padding:'5px'}"
      @selection-change="onItemTableSelectionChange"
      @row-dblclick="onItemRowClick"
    >
      <el-table-column
        type="selection"
        width="55"
      />

      <el-table-column
        prop="code"
        header-align="center"
        width="200"
        label="编码"
      />
      <el-table-column
        prop="name"
        header-align="center"
        width="200"
        label="名称"
      />
      <el-table-column
        prop="val"
        header-align="center"
        width="200"
        label="配置值"
      />

      <el-table-column label="上级配置" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          {{ row.parentInfo ? row.parentInfo.name : '' }}
        </template>
      </el-table-column>

    </el-table>

    <pagination
      :total="queryParams.total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="loadItemList"
    />

    <!-- edit-drawer -->
    <el-drawer
      ref="editDrawer"
      :title="dataForm.id ? '编辑' : '新增'"
      :visible.sync="showEditDrawer"
      direction="rtl"
      custom-class="edit-drawer"
      size="50%"
      :close-on-press-escape="drawerCloseOnEsc"
      :wrapper-closable="drawerWrapperClosable"
    >
      <div class="edit-drawer-content">
        <el-form ref="dataForm" :model="dataForm" :rules="dataFormRule" label-width="80px">

          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="上级配置" prop="name">
                <el-select v-model="dataForm.parentCode" placeholder="上级配置" style="width: 100%;" class="filter-item split-item">
                  <el-option
                    v-for="item in parentList"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="配置编码" prop="code">
                <el-input v-model.trim="dataForm.code" placeholder="请输入配置编码" :disabled="dataForm.id !== undefined" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="配置名称" prop="name">
                <el-input v-model.trim="dataForm.name" placeholder="请输入配置名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="23">
            <el-col :span="23">
              <el-form-item label="配置项值" prop="val">
                <el-input v-model.trim="dataForm.val" placeholder="请输入配置项值" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <div class="edit-drawer-footer">
        <el-button
          v-waves
          class="filter-item"
          plain
          size="mini"
          @click="showEditDrawer = false"
        >取消
        </el-button>

        <el-button
          v-waves
          class="filter-item"
          size="mini"
          type="primary"
          @click="onSaveData"
        >保存
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js'
import waves from '@/directive/waves'
import elHeightAdaptiveTable from '@/directive/el-table'
import Pagination from '@components/Pagination'

import { resetObject, fillObject } from '@utils/index'

import Settings from '@/settings'

import ConfigApi from '@api/sys/config'
import webMenuApi from '@api/iam/webMenu'
import appMenuApi from '@api/iam/appMenu'

let self

export default {
  name: 'SysConfigList',
  components: { Pagination },
  directives: { permission, waves, elHeightAdaptiveTable },
  data() {
    return {
      itemList: [],
      itemListLoading: false,
      itemTableSelectedCount: 0,
      showEditDrawer: false,
      drawerCloseOnEsc: Settings.drawerCloseOnEsc,
      drawerWrapperClosable: Settings.drawerWrapperClosable,
      currentSelectRole: undefined,
      parentList: [{
        code: 'ROOT',
        name: '无上级配置'
      }],
      dataForm: {
        id: undefined,
        code: undefined,
        name: undefined,
        parentCode: undefined,
        val: undefined,
        sortNo: undefined
      },
      queryParams: {
        parentCode: undefined,
        code: undefined,
        name: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dataFormRule: {
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { min: 1, max: 30, message: '编码长度在1到30个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 20, message: '配置名称长度在1到20个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  created() {
    self = this
    self.loadDependParams()
    this.loadItemList()
  },
  methods: {
    loadDependParams() {
      this.loadParentList()
    },
    loadParentList() {
      ConfigApi.fetchList({ pageSize: 99999999, parentCode: 'ROOT' }).then(response => {
        const { list } = response.data
        this.parentList.splice(1, this.parentList.length - 1, ...list)
      })
    },
    resetQueryParams() {
      resetObject(this.queryParams, undefined, ['pageNum', 'pageSize', 'total'])
      this.handleFilter()
    },
    handleFilter() {
      this.queryParams.pageNum = 1
      this.loadItemList()
    },
    loadItemList() {
      this.itemListLoading = true

      if (this.$refs.itemTable) {
        this.$refs.itemTable.clearSelection()
      }

      ConfigApi.fetchList(this.queryParams).then(response => {
        const { page } = response.data
        this.itemList.splice(0, this.itemList.length, ...page.records)
        this.queryParams.total = page.total
      }).finally(() => {
        this.itemListLoading = false
      })
    },
    onCreateItem() {
      this.openEditDrawer(null)
    },
    onEditItem() {
      if (!this.$refs.itemTable) {
        return
      } else if (this.$refs.itemTable.selection.length !== 1) {
        return
      }
      const item = this.$refs.itemTable.selection[0]
      this.openEditDrawer(item)
    },
    onItemTableSelectionChange(items) {
      this.itemTableSelectedCount = items.length
    },
    onItemRowClick(item) {
      this.openEditDrawer(item)
    },
    openEditDrawer(item) {
      if (item) {
        fillObject(this.dataForm, item)
      } else {
        resetObject(this.dataForm)
      }

      this.showEditDrawer = true
    },
    onSaveData() {
      const dataForm = this.$refs.dataForm
      dataForm.validate((valid) => {
        if (!valid) {
          return
        }
        this.doSaveData()
      })
    },
    doSaveData() {
      ConfigApi.save(this.dataForm).then(() => {
        this.showEditDrawer = false
        resetObject(this.dataForm)
        this.loadItemList()
      })
    },
    onRemoveItem() {
      if (!this.$refs.itemTable) {
        return
      } else if (this.$refs.itemTable.selection.length <= 0) {
        return
      }

      const items = this.$refs.itemTable.selection
      const ids = items.map((item) => item.id)
      this.$confirm('确定删除所选配置', '提示').then(() => {
        this.doRemoveItem(ids)
      })
    },
    doRemoveItem(ids) {
      ConfigApi.remove(ids).then(() => {
        this.loadItemList()
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .menu-container {
    max-height: calc(100vh - 160px);
    height: calc(100vh - 160px);
    padding-left: 10px;
    padding-right: 10px;
    width: 100%;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
